package com.hucc.redislock;

import com.hucc.redislock.command.RenewExpirationRedisCommand;

import java.util.Timer;
import java.util.TimerTask;

/**
 * 锁过期时间管理者
 */
public class LockExpireManager {
    private String lockName;

    private Timer timer = new Timer();

    /**
     * 登记要管理的 锁名称
     */
    public void register(String lockName) {
        this.lockName = lockName;
    }

    /**
     * 自动延期
     */
    public void automaticExtension(String threadName) {

        long delay = RedisLockContext.getRedisLockConfig().getLockWatchdogTimeout() / 3;
        long period = delay;

        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                RenewExpirationRedisCommand renewExpirationRedisCommand = new RenewExpirationRedisCommand(lockName, threadName);
                RedisLockContext.getRedisCommandExecutor().executeCommand(renewExpirationRedisCommand);
            }
        }, delay, period);

    }

    public void stopExtension() {
        timer.cancel();
    }
}
